// detail.js - 订单详情页面逻辑

Page({
  data: {
    order: {},
    orderStatusText: '',
    orderStatusDesc: '',
    loading: true
  },

  onLoad: function(options) {
    // 获取订单ID
    if (options.id) {
      this.orderId = options.id;
      this.loadOrderDetail();
    } else {
      wx.showToast({
        title: '订单ID不存在',
        icon: 'none',
        duration: 2000,
        complete: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }
  },

  // 加载订单详情
  loadOrderDetail: function() {
    this.setData({ loading: true });
    
    // 模拟请求，实际应调用后端API
    wx.request({
      url: 'https://api.example.com/orders/' + this.orderId,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          const order = res.data.data;
          this.setOrderData(order);
        } else {
          wx.showToast({
            title: '订单详情加载失败',
            icon: 'none'
          });
          console.error('加载订单详情失败:', res);
        }
      },
      fail: (err) => {
        // 模拟数据，用于开发测试
        const mockOrder = this.getMockOrder();
        this.setOrderData(mockOrder);
        console.error('请求失败，使用模拟数据:', err);
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 设置订单数据和状态文本
  setOrderData: function(order) {
    let statusText = '';
    let statusDesc = '';
    
    // 根据订单状态设置不同的文本描述
    switch(order.status) {
      case 'pending_payment':
        statusText = '待支付';
        statusDesc = '请在24小时内完成支付，超时订单将自动取消';
        break;
      case 'paid':
        statusText = '已支付';
        statusDesc = '我们已收到您的付款，正在为您准备商品';
        break;
      case 'processing':
        statusText = '处理中';
        statusDesc = '您的订单正在处理中，请耐心等待';
        break;
      case 'shipped':
        statusText = '已发货';
        statusDesc = '您的订单已发出，请注意查收';
        break;
      case 'delivered':
        statusText = '已送达';
        statusDesc = '您的订单已送达，请确认收货';
        break;
      case 'completed':
        statusText = '已完成';
        statusDesc = '感谢您的购买，期待下次光临';
        break;
      case 'canceled':
        statusText = '已取消';
        statusDesc = '订单已取消';
        break;
      case 'failed':
        statusText = '已失败';
        statusDesc = '订单支付失败，请重新尝试';
        break;
      default:
        statusText = '未知状态';
        statusDesc = '订单状态异常，请联系客服';
    }
    
    // 设置支付方式文本
    let paymentMethodText = '';
    if (order.payment_method === 'wechat') {
      paymentMethodText = '微信支付';
    } else if (order.payment_method === 'alipay') {
      paymentMethodText = '支付宝';
    }
    
    order.payment_method_text = paymentMethodText;
    
    this.setData({
      order: order,
      orderStatusText: statusText,
      orderStatusDesc: statusDesc
    });
  },

  // 模拟订单数据
  getMockOrder: function() {
    return {
      id: this.orderId || '2024051812345678',
      create_time: '2024-05-18 14:30:25',
      pay_time: '2024-05-18 14:35:10',
      status: 'paid',
      payment_method: 'wechat',
      total_amount: '128.50',
      goods_total_price: '118.50',
      delivery_fee: '10.00',
      discount_amount: '5.00',
      remark: '尽快发货，谢谢',
      address: {
        name: '张先生',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detail: '科技园南区10栋501室'
      },
      goods: [
        {
          id: 'g001',
          name: '高级运动鞋 舒适透气 减震耐磨',
          spec: '黑色 42码',
          image: 'https://example.com/images/goods1.jpg',
          current_price: '59.90',
          original_price: '79.90',
          num: 2
        }
      ]
    };
  },

  // 去支付
  goPayment: function() {
    wx.navigateTo({
      url: '/pages/order/payment?id=' + this.orderId
    });
  },

  // 取消订单
  cancelOrder: function() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消此订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟取消订单请求
          this.setData({ loading: true });
          
          wx.request({
            url: 'https://api.example.com/orders/' + this.orderId + '/cancel',
            method: 'POST',
            success: (res) => {
              if (res.data && res.data.code === 0) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success',
                  complete: () => {
                    this.loadOrderDetail(); // 重新加载订单详情
                  }
                });
              } else {
                wx.showToast({
                  title: '取消订单失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络异常，请重试',
                icon: 'none'
              });
            },
            complete: () => {
              this.setData({ loading: false });
            }
          });
        }
      }
    });
  },

  // 确认收货
  confirmReceipt: function() {
    wx.showModal({
      title: '确认收货',
      content: '确认已收到商品吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟确认收货请求
          this.setData({ loading: true });
          
          wx.request({
            url: 'https://api.example.com/orders/' + this.orderId + '/confirm',
            method: 'POST',
            success: (res) => {
              if (res.data && res.data.code === 0) {
                wx.showToast({
                  title: '已确认收货',
                  icon: 'success',
                  complete: () => {
                    this.loadOrderDetail(); // 重新加载订单详情
                  }
                });
              } else {
                wx.showToast({
                  title: '确认收货失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络异常，请重试',
                icon: 'none'
              });
            },
            complete: () => {
              this.setData({ loading: false });
            }
          });
        }
      }
    });
  },

  // 联系商家
  contactMerchant: function() {
    wx.showActionSheet({
      itemList: ['客服电话', '在线客服'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 拨打客服电话
          wx.makePhoneCall({
            phoneNumber: '400-123-4567'
          });
        } else if (res.tapIndex === 1) {
          // 跳转到在线客服页面
          wx.navigateTo({
            url: '/pages/customer-service/index'
          });
        }
      }
    });
  },

  // 删除订单
  deleteOrder: function() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此订单吗？删除后将无法恢复。',
      success: (res) => {
        if (res.confirm) {
          // 模拟删除订单请求
          this.setData({ loading: true });
          
          wx.request({
            url: 'https://api.example.com/orders/' + this.orderId + '/delete',
            method: 'POST',
            success: (res) => {
              if (res.data && res.data.code === 0) {
                wx.showToast({
                  title: '订单已删除',
                  icon: 'success',
                  complete: () => {
                    setTimeout(() => {
                      wx.navigateBack();
                    }, 1500);
                  }
                });
              } else {
                wx.showToast({
                  title: '删除订单失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络异常，请重试',
                icon: 'none'
              });
            },
            complete: () => {
              this.setData({ loading: false });
            }
          });
        }
      }
    });
  },

  // 评价订单
  reviewOrder: function() {
    wx.navigateTo({
      url: '/pages/order/review?id=' + this.orderId
    });
  },

  // 再次购买
  rebuy: function() {
    // 将商品添加到购物车并跳转到结算页面
    const goods = this.data.order.goods;
    
    // 模拟添加到购物车
    wx.setStorageSync('rebuy_goods', goods);
    
    wx.showToast({
      title: '已将商品添加到购物车',
      icon: 'success',
      complete: () => {
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/order/checkout?rebuy=true'
          });
        }, 1500);
      }
    });
  }
});